﻿using CSRedis;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MetroDataApi.Models
{
    public class UploadMonitorPointsHelper
    {
        /// <summary>
        /// 满足审核要求的测项
        /// </summary>
        public static List<string> ShouldReviewMonitorType = new List<string> { "沉降", "收敛", "平面位移", "倾斜" };

        /// <summary>
        /// 上传前的检查
        /// </summary>
        /// <param name="prjId"></param>
        /// <param name="point"></param>
        /// <param name="shoudPreview"></param>
        /// <returns></returns>
        public static string UploadPreCheck(int prjId, result point, out bool shoudPreview)
        {
            shoudPreview = false;
            using (var db = new MetroDataDataContext())
            {
                var prj = db.Projects.SingleOrDefault(p => p.PrjId == prjId);
                if (prj == null) return string.Format("无效的prjId:{0},该工程不存在", prjId);
                var date = DateTime.Parse(point.time);
                var pt = db.MonitorPointsDictionary.SingleOrDefault(p => p.PrjId == prjId && p.Name == point.name);
                if (pt == null)
                {
                    return string.Format("点'{0}'尚未配置,先配置后再上传", point.name);
                }
                //判定是否需要审核
                else if (UploadMonitorPointsHelper.ShouldReviewMonitorType.IndexOf(pt.MonitorType) >= 0)
                {
                    var diff = Math.Abs((date - DateTime.Now).Days);
                    if (diff < 7)
                    {
                        shoudPreview = true;
                    }
                }
                return "";
            }
        }


        public static void PublishReviewEventToRedis(int prjId, string time)
        {
            using (var redis = new RedisClient("localhost"))
            {
                using (var db = new MetroDataDataContext())
                {
                    var prjName = db.Projects.SingleOrDefault(p => p.PrjId == prjId).Name;
                  
                    var newUploadData = new
                    {
                        prjId = prjId,
                        date = time,
                        prjName = prjName,
                        notify = 1
                    };
                    //发布新数据上传的通知
                    redis.Publish("metroProjects:newDataUpload", JsonConvert.SerializeObject(newUploadData));
                }

            }
        }


    }
}